package com.jerkin.coder;

import com.jerkin.serial.ObjectSerializer;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

/**
 * @version V1.0
 * @ClassName: DecoderHelper
 * @Description:解码工具类
 * @author: huhongzhi
 * @date: 2021/4/17 16:17
 */
public class DecoderHelper extends ByteToMessageDecoder {

    private Class<?> genericClass;
    private ObjectSerializer objectSerializer;

    public DecoderHelper(Class<?> genericClass, ObjectSerializer serializer) {
        this.genericClass = genericClass;
        this.objectSerializer = serializer;
    }

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        if (byteBuf.readableBytes() < 4) {
            return;
        }
        byteBuf.markReaderIndex();
        int dataLength = byteBuf.readInt();
        if (byteBuf.readableBytes() < dataLength) {
            byteBuf.resetReaderIndex();
            return;
        }
        byte[] data = new byte[dataLength];
        byteBuf.readBytes(data);
        list.add(objectSerializer.deserialize(genericClass, data));
    }
}
